package cn.javadog.algorithm.m1_100;


/**
 * 罗马数字转整数
 * https://leetcode-cn.com/problems/roman-to-integer/
 * @author Sprite
 */
public class Algorithm13 {
	public static void main(String[] args) {
		System.out.println(romanToInt("MMCCCVII"));
	}


	public static int romanToInt(String s) {
		boolean handleNext = false;
		int result = 0;
		for (int i = 0; i < s.length(); i++) {
			char c = s.charAt(i);
			boolean hasNext = i+1 < s.length();
			boolean hasBefore2 = i>1;

			switch (c){
				case 'M':
					if (!handleNext){
						result += 1000;
					}
					handleNext = false;
					break;
				case 'D':
					if (!handleNext){
						result += 500;
					}
					handleNext = false;
					break;
				case 'C':
					if (handleNext){
						handleNext = false;
					}else if (hasNext && 'M' == s.charAt(i+1)){
						result += 900;
						handleNext = true;
					}else if (hasNext && 'D' == s.charAt(i+1)){
						result += 400;
						handleNext = true;
					}else {
						result += 100;
						handleNext = false;
					}
					break;
				case 'L':
					if (!handleNext){
						result += 50;
					}
					handleNext = false;
					break;
				case 'X':

					if (handleNext){
						handleNext = false;
					}else if (hasNext && 'L' == s.charAt(i+1)){
						result += 40;
						handleNext = true;
					}else if (hasNext && 'C' == s.charAt(i+1)){
						result += 90;
						handleNext = true;
					}else {
						result += 10;
						handleNext = false;
					}
					break;
				case 'V':
					if (!handleNext){
						result += 5;
					}
					handleNext = false;
					break;
				case 'I':
					if (handleNext && hasBefore2 && 'I' == s.charAt(i-2)){
						result += 3;
						handleNext = false;
					}else if (handleNext && hasNext && 'I' != s.charAt(i+1)){
						result += 2;
						handleNext = false;
					}else if (!handleNext && hasNext && 'I' != s.charAt(i+1) && 'X' != s.charAt(i+1) && 'V' != s.charAt(i+1)){
						result += 1;
						handleNext = false;
					}else if (hasNext && 'X' == s.charAt(i+1)){
						result += 9;
						handleNext = true;
					}else if (hasNext && 'V' == s.charAt(i+1)){
						result += 4;
						handleNext = true;
					}else if (!hasNext && handleNext){
						result += 2;
						handleNext = false;
					}else if (hasNext){
						handleNext = true;
					}else {
						result += 1;
						handleNext = false;
					}
					break;
				default:
					break;
			}
		}
		return result;
	}
}
